import axios from 'axios'
import qs from 'qs'
import toast from './toast'

function processResponse (res) {
  if (res.status === 200) {
    if (res.data.code === 0) {
      toast.toast('哎呀，网络连接出错啦')
    }
    return res.data
  }
  return null
}

function processRequest (method, url, options) {
  return axios({
    url,
    method,
    params: options.params,
    data: qs.stringify(options.data),
    // 你可以使用validateStatus设置选项自定义HTTP状态码的错误范围。
    validateStatus: status => status >= 200 && status <= 500
  }).then(res => processResponse(res)).catch((res) => {
    window.alert('网络错误，请稍后重试')
    console.log(res)
  })
}

export default {
  get (url, params) {
    return processRequest('get', url, { params })
  },
  post (url, data) {
    return processRequest('post', url, { data })
  },
  put (url, data) {
    return processRequest('put', url, { data })
  },
  delete (url) {
    return processRequest('delete', url, {})
  }
}
